package com.jeomo.sys.starter.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.dto.PageQueryDto;
import com.jeomo.common.core.dto.PageResponseDto;
import com.jeomo.common.core.enums.SexEnum;
import com.jeomo.common.core.exception.OperationNotAllowException;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.common.util.RedisUtil;
import com.jeomo.shiro.util.LoginSessionUtil;
import com.jeomo.shiro.util.PasswordUtil;
import com.jeomo.sys.api.enums.UserStatusEnum;
import com.jeomo.sys.starter.entity.User;
import com.jeomo.sys.starter.entity.UserRole;
import com.jeomo.sys.starter.mapper.UserMapper;
import com.jeomo.sys.starter.service.IOrgService;
import com.jeomo.sys.starter.service.IRoleService;
import com.jeomo.sys.starter.service.IUserRoleService;
import com.jeomo.sys.starter.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jeomo
 * @since 2019-03-22
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    RedisUtil redisUtil;

    final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    IOrgService orgService;

    @Resource
    IUserRoleService userRoleService;

    @Resource
    IRoleService roleService;

    @Override
    public User queryByUsername(String username) {
        return this.baseMapper.queryByUsername(username);
    }

    @Override
    @Cacheable(cacheNames = "user::page", key = "#request.pageNumber")
    public PageResponseDto pageSearch(PageQueryDto dt) {
//        Object cache = redisUtil.get("sys:user:page:" + dt.getPageNumber() + ":" + dt.getPageSize());
//        if(cache != null) {
//            return (PageResponseDto) cache;
//        }
        PageResponseDto dto = super.pageSearch(dt);
//        redisUtil.set("sys:user:page:" + dt.getPageNumber() + ":" +dt.getPageSize(), dto);
        return dto;
    }

    /**
     * 删除用户，删除用户的同时，删除响应的角色信息
     * @param userCode
     * @return
     */
    @Override
    public boolean removeById(Serializable userCode) {
        User user = getById(userCode);
        if(user != null) {
            if(ADMIN_USER.equals(user.getUsername())) {
                throw new OperationNotAllowException("不能删除管理员账户");
            }
        }
        userRoleService.deleteByUserCode((String) userCode);
        return super.removeById(userCode);
    }

    @Override
    public boolean save(User user, List<String> roles) {
        if(StringUtils.isEmpty(user.getTopOrgCode())){
            user.setTopOrgCode(LoginSessionUtil.getCurrentLoginInfo().getCurrentTopOrgCode());
        }
        if(StringUtils.isEmpty(user.getCode()) && StringUtils.isNotEmpty(user.getPassword())) {
            //编辑状态下，不可以修改密码
            user.setPassword(PasswordUtil.entryPassword(user.getTopOrgCode(), user.getUsername(), user.getPassword()));
            user.setStatus(UserStatusEnum.NORMAL);
        }
        if(user.getSex() == null) {
            user.setSex(SexEnum.SECRET);
        }
        boolean result = super.saveOrUpdate(user);
        if(result && roles != null) {
            userRoleService.deleteByUserCode(user.getCode());
            List<UserRole> urs = new ArrayList<>();
            for(String role : roles){
                UserRole ur = new UserRole(user.getCode(), role);
                urs.add(ur);
            }
            userRoleService.saveBatch(urs);
        }
        return result;
    }
}
